package com.filipesilvestrim.util
{
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.ui.Keyboard;
	
	public class Console
	{
		static private var COUT_STR			: String = ">>> ";
		static private var CIN_STR			: String = "<<< ";
		static private var _scope 			: Sprite;
		static private var _txt 			: TextField;
		static private var _keyPressed 		: Boolean = false;
		static private var _lenBefInsert 	: int;
		static private var _callRead		: Function;
		
		static public function init (scope : Sprite ) : void
		{
			_scope = scope;
			_scope.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			
			_txt 			= new TextField();
			_txt.type		= TextFieldType.INPUT;
			_txt.border		= false;
			_txt.selectable = false;
			_txt.autoSize 	= "left";
			
			_scope.addChild(_txt);
		}
		
		static public function write ( s : String ) : void
		{
			_txt.appendText(COUT_STR + s + "\n");
		}
		
		static public function read (callback : Function) : void
		{
			_callRead = callback;
			_txt.appendText(CIN_STR);
			_lenBefInsert = _txt.length;
		}
		
		static private function onKeyDown ( e : KeyboardEvent) : void
		{
			if (e.charCode == Keyboard.ENTER)
			{
				_txt.appendText("\n");
				_callRead(_txt.text.substring(_lenBefInsert,_txt.length));
			}
		}
	}
}